package uk.ac.aber.paws.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;

import uk.ac.aber.paws.client.constants.Constants;
import uk.ac.aber.paws.client.core.Initiator;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * ServiceOperations.java
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class ServiceOperations {

	public static boolean isServiceStopped() {
		
		String line = "";
		
		Process p;
		
		try {
			p = Runtime.getRuntime().exec("sc query pawsclient");
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			
			while ((line = reader.readLine()) != null) {
			
				if (line.trim().startsWith("STATE")) {
					
					if (line.indexOf("STOPPED") > -1) {
						return true;
					}
				}	
			}
			
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	public static void switchService(boolean start) {
		
		try {
			Process p;
			
			if (start) {
				 p = Runtime.getRuntime().exec("net start pawsclient");	
			}
			else {
				p = Runtime.getRuntime().exec("net stop pawsclient");
			}
			
			p.waitFor();
			
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
